import {createRouter,createWebHistory} from 'vue-router'



import DashboardView from '../pages/DashboardView.vue'
import RegistrationListView from '../pages/RegistrationListView.vue';
import ConsultationRecordView from '../pages/ConsultationRecordView.vue';
import SchedulingView from '../pages/SchedulingView.vue';
import SystemSettingView from '../pages/SystemSettingView.vue';
import RoleManagement from '../pages/RoleManagement.vue';
import OperationLog from '../pages/OperationLog.vue';
import UserManagement from '../pages/UserManagement.vue';
import {ElMessage} from "element-plus";
import {UserStore} from "../store/pcUser.js";
import Login from "../pages/Login.vue";
import Home from "../pages/home.vue";
const routes=[

	

{
	path:'/home',
	name:'Home',
	component:Home,
	redirect: '/home/dashboard',
	children:[
		      { path: 'dashboard', component: DashboardView },
		      { path: 'registration', component: RegistrationListView },
		      { path: 'consultation-record', component: ConsultationRecordView },
		      { path: 'scheduling', component: SchedulingView },
		      { path: 'system-setting', component: SystemSettingView },
			  { path: 'roleManagement',component: RoleManagement},
			  { path: 'userManagement',component: UserManagement},
			  { path: 'operationLog',component: OperationLog},
	]
},
	{
		path:'/',
		redirect:'/login'
	},
	{
		path:'/login',
		name:'Login',
		component:Login
	},


]
const router = createRouter({
  history: createWebHistory(),  
  routes  // 应用路由规则
})

const whiteList = ['/login']
router.beforeEach((to, from, next) => {
	const userStore = UserStore()


	// 1. 白名单页面直接放行
	if (whiteList.includes(to.path)) {
		next()
		return
	}

	// 2. 未登录：强制跳转到登录页
	if (!userStore.userInfo || !userStore.userInfo.pc_user_id) {
		ElMessage.error('请先登录')
		next('/login')
		return
	}

	// 3. 已登录：校验权限
	const allowedPaths = userStore.userInfo.list || [] // 用户有权访问的路径列表
	// 特殊处理：父路由/home允许访问（但其子路由会被校验）
	const isAllowed = to.path === '/home' || allowedPaths.includes(to.path)

	if (isAllowed) {
		// 有权限：放行
		next()
	} else {
		// 无权限：提示并跳转到首页
		ElMessage.error('您没有访问该页面的权限')
		next('/home') // 跳转到用户有权限的首页
	}
})

export default router


